package com.molihub.controller;

import com.alibaba.fastjson.JSONObject;
import com.molihub.component.MyWebSocketHandler;
import com.molihub.entity.*;
import com.molihub.utils.LogUtils;
import com.molihub.utils.StringUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * @ClassName: CommentController
 * @Description: 处理评论相关的控制器
 * @author: GGBOY
 * @date 2020/2/15 21:36
 * @Version: 1.0
 **/
@Controller
public class CommentController extends BaseController {
    private static Logger logger = LogUtils.getInstance(CommentController.class);

    /**
     * 发布评论
     *
     * @param articleId 评论所属文章ID
     * @param comment   评论内容
     * @param userName  发表评论的用户名
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/2/16
     */
    @ResponseBody
    @PostMapping("publish/comment/{userName}/{comment}/{articleId}")
    public String publishComment(@PathVariable Integer articleId, @PathVariable String comment, @PathVariable String userName) {

        User user = userService.getUserByUserName(userName);
        if (user == null) {
            return "ERROR";
        }
        // 封装评论信息
        ArticleComment articleComment = ArticleComment.builder()
                .articleId(articleId).commentContent(comment)
                .commentTime(new Date()).userId(user.getUserId())
                .build();
        // 添加评论记录
        Integer commentId = articleCommentService.addCommentRecord(articleComment);
        Article article = articleService.getArticleById(articleId);
        // 通知文章作者有人评论
        Integer receiveUserId = article.getUserId();
        User receiveUser = userService.getUserById(receiveUserId);
        // 封装消息
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("A", user.getUserName());
        jsonObject.put("B", receiveUser.getUserName());
        jsonObject.put("flag", "6");
        jsonObject.put("aUserInfo", user);
        jsonObject.put("bUserInfo", receiveUser);

        if (article.getArticleTitle() == null) {
            // 表明点赞的是状态，那就显示点赞的状态部分内容
            jsonObject.put("content", "评论了你的<h5>" + StringUtils.cutStr(article.getArticleContent(), 20) + "</h5>");
        } else {
            jsonObject.put("content", "评论了你的<h5>" + article.getArticleTitle() +"</h5>");
        }
        // 封装通信信息
        RequestMessage message = RequestMessage.builder()
                .aUserId(user.getUserId())
                .bUserId(receiveUserId)
                .isReceive(0).flag(6)
                .messageContent(jsonObject.toJSONString())
                .build();
        // 将消息记录存表
        requestMessageService.addMessage(message);
        // 封装Message
        Message message1 = Message.builder().messageTime(new Date())
                .fromUserId(user.getUserId()).toUserId(receiveUser.getUserId())
                .articleId(articleId).articleCommentId(commentId).isLooked(0).build();
        messageService.addRecord(message1);
        // 发送消息
        MyWebSocketHandler.aSendMessageToB(user.getUserId(), receiveUserId, jsonObject.toJSONString());
        return "OK";
    }

    /**
     * 回复评论
     *
     * @param articleId       评论所属的文章ID
     * @param comment         评论内容
     * @param targetName      回复的评论的用户名
     * @param userName        回复的用户名
     * @param targetCommentId 回复评论的评论ID
     * @return java.lang.String
     * @author GGBOY
     * @date 2020/2/16
     */
    @ResponseBody
    @PostMapping("publish/reply/{userName}/{targetName}/{comment}/{articleId}/{targetCommentId}")
    public String replyComment(@PathVariable Integer articleId, @PathVariable String comment,
                               @PathVariable String targetName, @PathVariable String userName, @PathVariable Integer targetCommentId) {
        logger.info("文章ID: " + articleId + " 目标评论ID：" + targetCommentId + " 目标评论用户名:" + targetName + " 发布回复的用户名：" + userName);
        // 发布回复的用户
        User user = userService.getUserByUserName(userName.trim());
        // 被回复的用户
        User targetUser;
        if (userName.equals(targetName)) {
            targetUser = user;
        } else {
            targetUser = userService.getUserByUserName(targetName.trim());
        }
        if (user == null || targetUser == null) {
            return "ERROR";
        } else {
            ArticleComment articleComment = ArticleComment.builder()
                    .articleId(articleId).commentContent(comment)
                    .commentTime(new Date()).userId(user.getUserId())
                    .toUserId(targetUser.getUserId()).toId(targetCommentId)
                    .build();
            articleCommentService.addCommentRecord(articleComment);

            Article article = articleService.getArticleById(articleId);
            // 通知评论作者有人回复评论
            // 封装消息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("A", userName);
            jsonObject.put("B", targetName);
            jsonObject.put("flag", "6");
            jsonObject.put("aUserInfo", user);
            jsonObject.put("bUserInfo", targetUser);
            jsonObject.put("content", "回复了你的<h5>" +
                    StringUtils.cutStr(comment, 20) + "</h5>评论");

            // 封装通信信息
            RequestMessage message = RequestMessage.builder()
                    .aUserId(user.getUserId())
                    .bUserId(targetUser.getUserId())
                    .isReceive(0).flag(6)
                    .messageContent(jsonObject.toJSONString())
                    .build();
            // 将消息记录存表
            requestMessageService.addMessage(message);
            // 封装Message
            Message message1 = Message.builder().messageTime(new Date())
                    .fromUserId(user.getUserId()).toUserId(targetUser.getUserId())
                    .articleId(articleId).articleCommentId(articleComment.getArticleCommentId()).isLooked(0).build();
            messageService.addRecord(message1);
            // 发送消息
            MyWebSocketHandler.aSendMessageToB(user.getUserId(), targetUser.getUserId(), jsonObject.toJSONString());
            return "OK";
        }
    }
}
